//
//  APOLoginViewController.m
//  Apallo
//
//  Created by Jason Poh on 19/8/14.
//  Copyright (c) 2014 Apallo. All rights reserved.
//

#import "APOLoginViewController.h"
#import "APOMainViewController.h"
#import "APOIVLELogin.h"
#import "APOLAPI_Login.h"
#import "APOApalloAPI.h"
#import "APOUser.h"
#import "APOSaveUtility.h"

@interface APOLoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *matricNoTxtField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTxtField;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loginActivityIndicator;


@property (strong, nonatomic) APOIVLELogin *ivle_login;
@property (strong, nonatomic) UIAlertView *error_invalid_login_alert;

@end

@implementation APOLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
       
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view
    
    //Hide activity indicator first
    self.loginActivityIndicator.hidden = YES;
    
    /* Need to set borderWidth to change borderColor */
    self.matricNoTxtField.layer.borderWidth = 1.0f;
    self.passwordTxtField.layer.borderWidth = 1.0f;
    
    self.matricNoTxtField.layer.borderColor = [[UIColor whiteColor]CGColor];
    self.passwordTxtField.layer.borderColor = [[UIColor whiteColor]CGColor];
    
    self.ivle_login = [[APOIVLELogin alloc]init];
    self.error_invalid_login_alert = [[UIAlertView alloc] initWithTitle: @"Unable to login to IVLE" message: @"Please check your matric no. and/or password." delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self
            selector:@selector(ivleLoginCallback:)
            name: IVLE_LOGIN_NOTIFICATION
            object:nil];
    
    [center addObserver:self
            selector:@selector(lapiLoginCallback:)
            name: LAPI_LOGIN_NOTIFICATION
            object:nil];
    
    [center addObserver:self
            selector:@selector(apalloApiCallback:)
            name: APALLO_API_NOTIFICATION
            object:nil];
    
}

- (void)ivleLoginCallback:(NSNotification *)notification //use notification method and logic
{
    
    NSString *key = IVLE_TOKEN;
    NSDictionary *dictionary = [notification userInfo];
    NSString *token = [dictionary valueForKey:key];
    NSLog(@"LOGIN_STATUS: %@",token);
    if([token isEqual: @"FAILED"]){
        [self hide_login_activity_indicator];
        [self.error_invalid_login_alert show];
        [_loginBtn setEnabled:YES];
    }else{
        //Successfully logged in
        
        //Validating token
        [APOUser getUser].token = token;
        [APOLAPI_Login validate:token];
        
        
    }
}

- (void)apalloApiCallback:(NSNotification *)notification //use notification method and logic
{
    
//    NSDictionary *dictionary = [notification userInfo];
//    
//    if(dictionary[LAPI_VALIDATE])
//    {
//    
//    }
    
}


- (void)lapiLoginCallback:(NSNotification *)notification //use notification method and logic
{
    
    NSDictionary *dictionary = [notification userInfo];
    
    if(dictionary[LAPI_VALIDATE])
    {
        NSString * validate_result = [dictionary valueForKey:LAPI_VALIDATE];
        if([validate_result isEqual:@"SUCCESS"]){
            [APOUser getUser].isSuccessfullyLoggedIn = YES;
            NSLog(@"Token Validated. Switching View to Main View & Requesting userid, fullname and email ...");
            [self hide_login_activity_indicator];
            [self switchToMainView];
            [APOApalloAPI getInfo:[APOUser getUser].token];
        } else {
            //Token is invalid
            [APOUser getUser].token = @"";
            [APOUser getUser].isSuccessfullyLoggedIn = NO;
        }
    }
    
}
             
- (void) switchToMainView
{
    [self performSegueWithIdentifier:@"loginToMainSegue" sender: self];
}

- (void) switchToProfileUpdate
{
    [self performSegueWithIdentifier:@"loginToProfileUpdate" sender: self];
}
             

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)textFieldShouldReturn:(UITextField*)textField
{
    [textField resignFirstResponder];
    if(textField == self.matricNoTxtField){
        [self.passwordTxtField becomeFirstResponder];
    } else if(textField == self.passwordTxtField) {
        [self.loginBtn sendActionsForControlEvents:UIControlEventTouchUpInside];
        return YES;
    }
    return NO;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)login_clicked:(UIButton *)sender {
    //Disable button first
    [sender setEnabled:NO];
    [self show_login_activity_indicator];
    
    NSString * matric_no = self.matricNoTxtField.text;
    NSString * password = self.passwordTxtField.text;
    NSLog(@"Login button pressed");
    NSLog(@"Matric No: %@", matric_no);
    NSLog(@"Password: %@", password);
    
    [_ivle_login login:matric_no :password];
    
}

- (void) show_login_activity_indicator
{
    self.loginActivityIndicator.hidden = NO;
    [self.loginActivityIndicator startAnimating];
}

- (void) hide_login_activity_indicator
{
    self.loginActivityIndicator.hidden = YES;
    [self.loginActivityIndicator stopAnimating];
}

@end
